# -*- coding: utf-8 -*-


from conf.entity.module.grpc_config import GrpcConfig
from com.maycur.grpc.base.grpc_entity import GrpcFullMapping
from com.maycur.grpc.lark.markdown_maker import MarkdownTable, MarkdownRow


class IndexCounter:
    idx: int

    def __init__(self):
        self.idx = 1

    def get_and_increment(self):
        res = str(self.idx)
        self.idx += 1
        return res


class LarkDocumentBuilder(object):
    config: GrpcConfig
    mapping: GrpcFullMapping
    markdown_table: MarkdownTable
    counter: IndexCounter
    result: bool

    def __init__(self, config: GrpcConfig, mapping: GrpcFullMapping):
        self.config = config
        self.mapping = mapping
        self.counter = IndexCounter()
        """
        the 4 columns:
            ice servant class name
            ice method name
            gRPC servant class name
            gRPC method name
        """
        self.markdown_table = MarkdownTable(5)
        table_header = MarkdownRow(5, is_header=True)
        table_header.add_cells('序号', '类名', '方法名', '类名', '方法名')
        self.markdown_table.set_header(table_header)

        if len(self.mapping.ice.ice_2_grpc_method_groups) > 0:
            for group_item in self.mapping.ice.ice_2_grpc_method_groups:
                if len(group_item.methods) > 0:
                    first_row = MarkdownRow(5)
                    first_item = group_item.methods[0]
                    first_row.add_cells(self.counter.get_and_increment(),
                                        group_item.ice_servant, first_item.ice_method,
                                        group_item.grpc_servant, first_item.grpc_method)
                    self.markdown_table.add_row(first_row)
                    for i in range(1, len(group_item.methods)):
                        the_item = group_item.methods[i]
                        the_row = MarkdownRow(5)
                        the_row.add_cells(self.counter.get_and_increment(),
                                          '', the_item.ice_method, '', the_item.grpc_method)
                        self.markdown_table.add_row(the_row)
        self.result = True

    def make_markdown_table(self):
        table_str = self.markdown_table.make()
        print('======> the servant markdown table is as follows <=== \n\n')
        print(table_str)
